package com.andaily.domain.developer.loader;

import com.andaily.domain.developer.Sprint;
import com.andaily.domain.developer.SprintMeeting;
import com.andaily.domain.developer.SprintRepository;
import com.andaily.domain.dto.developer.SprintMeetingDto;
import com.andaily.domain.dto.developer.SprintMeetingOverviewDto;
import com.andaily.domain.dto.developer.SprintSimpleDto;
import com.andaily.domain.shared.paginated.PaginatedLoader;
import com.andaily.web.context.BeanProvider;

import java.util.List;
import java.util.Map;

/**
 * Date: 13-10-2
 *
 * @author Shengzhao Li
 */
public class SprintMeetingOverviewDtoLoader {

    private transient SprintRepository sprintRepository = BeanProvider.getBean(SprintRepository.class);
    private SprintMeetingOverviewDto overviewDto;

    public SprintMeetingOverviewDtoLoader(SprintMeetingOverviewDto overviewDto) {
        this.overviewDto = overviewDto;
    }

    public SprintMeetingOverviewDto load() {
        loadAvailableSprints();
        loadPaginated();
        return overviewDto;
    }

    private void loadPaginated() {
        final Map<String, Object> map = overviewDto.queryParams();
        overviewDto = overviewDto.load(new PaginatedLoader<SprintMeetingDto>() {
            @Override
            public List<SprintMeetingDto> loadList() {
                List<SprintMeeting> meetings = sprintRepository.findMeetings(map);
                return SprintMeetingDto.toDtos(meetings);
            }

            @Override
            public int loadTotalSize() {
                return sprintRepository.totalMeetings(map);
            }
        });
    }

    private void loadAvailableSprints() {
        List<Sprint> sprints = sprintRepository.findSprints(false);
        List<SprintSimpleDto> sprintDtos = overviewDto.getSprintDtos();
        for (Sprint sprint : sprints) {
            sprintDtos.add(new SprintSimpleDto(sprint));
        }
    }
}
